package com.jacky.iot.resources;

import org.eclipse.californium.core.CoapResource;
import org.eclipse.californium.core.coap.CoAP;
import org.eclipse.californium.core.coap.OptionSet;
import org.eclipse.californium.core.coap.Response;
import org.eclipse.californium.core.network.Exchange;
import org.eclipse.californium.core.observe.ObserveRelation;
import org.eclipse.californium.core.server.resources.CoapExchange;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static org.eclipse.californium.core.coap.MediaTypeRegistry.TEXT_PLAIN;

public class ObservableResource extends CoapResource {


    private String status = "Initial Status";

    @Override
    public void handleGET(CoapExchange exchange) {
        System.out.println("ObservableResource.....");
        exchange.respond(CoAP.ResponseCode.CONTENT, status, 0);
    }

    public void updateStatus(String newStatus) {
        status = newStatus;
        changed(); // 通知所有观察者
    }

    public ObservableResource(String name) {
        super(name);
        setObservable(true); // enable observing
        setObserveType(CoAP.Type.CON); // configure the notification type to CONs
        getAttributes().setObservable(); // m

        Timer timer = new Timer("OBSERVE", true);
        timer.schedule(new TimeTask(), TimeUnit.SECONDS.toMillis(1), 500);
    }

    private class TimeTask extends TimerTask {

        @Override
        public void run() {
            status = getTime();
            // Call changed to notify subscribers
            changed();
        }
    }

    private String getTime() {
        DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        Date time = new Date();
        return dateFormat.format(time);
    }


}
